package com.dolphin.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dolphin.commons.ScheduledTaskAnnotation;
import com.dolphin.commons.SpringBeanUtils;
import com.dolphin.config.PostAppRunner;
import com.dolphin.model.ScheduledTask;
import com.dolphin.service.ScheduledTaskServices;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * 描述:
 * ${DESCRIPTION}
 *
 * @author 小海豚
 * @create 2022-10-23 22:15
 * 个人博客地址：https://www.nonelonely.com
 */
@Component
public class InitComponent {
    private final static Logger LOGGER = LoggerFactory.getLogger(InitComponent.class);

    @Autowired
    private  ScheduledTaskServices scheduledTaskServices;

    /*/**
     * @title 定时
     * @description []
     * @author
     * @updateTime 2022/10/23 22:16
     * @throws
     */
    public void initScheduledTask() {
        try {
            //自动获取所有的定时任务 保存到表里
            Map<String, Object> beans = SpringBeanUtils.getApplicationContext().getBeansWithAnnotation(ScheduledTaskAnnotation.class);
            for (String beanName : beans.keySet()) {
                Object bean = beans.get(beanName);
                ScheduledTask scheduledTaskByTaskKey = scheduledTaskServices.getScheduledTaskByTaskKey(beanName);
                if (scheduledTaskByTaskKey != null) {
                    continue;
                }
                // 依次获取到 使用了该注解的对象
                Class<?> aClass = AopUtils.getTargetClass(bean);
                ScheduledTaskAnnotation scheduledTaskAnnotation = aClass.getDeclaredAnnotation(ScheduledTaskAnnotation.class);
                ScheduledTask scheduledTaskQuery = new ScheduledTask();
                scheduledTaskQuery.setTaskKey(beanName);
                scheduledTaskQuery.setInitStartFlag(scheduledTaskAnnotation.initStartFlag());
                scheduledTaskQuery.setTaskDesc(scheduledTaskAnnotation.taskDesc());
                scheduledTaskQuery.setTaskCron(scheduledTaskAnnotation.taskCron());
                scheduledTaskServices.saveOrUpdate(scheduledTaskQuery);
            }
            LOGGER.info(" >>>>>> 项目启动完毕, 开启 => 需要自启的任务 开始!");
            ScheduledTask scheduledTaskQuery = new ScheduledTask();
            scheduledTaskQuery.setInitStartFlag(1);
            QueryWrapper<ScheduledTask> userQueryWrapper = new QueryWrapper<>(scheduledTaskQuery);
            List<ScheduledTask> scheduledTaskBeanList = scheduledTaskServices.list(userQueryWrapper);
            scheduledTaskServices.initAllTask(scheduledTaskBeanList);
            LOGGER.info(" >>>>>> 项目启动完毕, 开启 => 需要自启的任务 结束！");
        } catch (Exception e) {
            LOGGER.error("自启的任务失败{}", e.getMessage());
        }
    }
}
